package com.media.Media;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Size;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class VideoActivity extends Activity {

	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private Button buttonStart;
	private Button buttonStop;	
	private Button buttonSwitchVideo;
	
	private String videoName;
	private String fullPath;
	private MediaRecorder recorder;
	private Camera mCamera;
	private int cameraId;
	private int cameraCurrentId;
	private int numCamera;
	private List<Size> mSupportedPreviewSizes;
	
	private boolean isPreview = false;//是否在浏览中

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	//	requestWindowFeature(Window.FEATURE_NO_TITLE);
	//	this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.video);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		mSurfaceView = (SurfaceView) findViewById(R.id.videoView);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); // 设置该SurfaceView自己不维护缓冲
		buttonStart = (Button) findViewById(R.id.start);
		buttonStop = (Button) findViewById(R.id.stop);
		buttonSwitchVideo = (Button) findViewById(R.id.switchVideo);
		buttonStart.setClickable(false);
	//	mSurfaceHolder.setKeepScreenOn(true);
	//	mSurfaceHolder.setFixedSize(320, 240);
		
		
		numCamera = Camera.getNumberOfCameras();
		CameraInfo info = new CameraInfo();
        for(int i = 0;i< numCamera;i++){
            Camera.getCameraInfo(i, info);
            if(info.facing == CameraInfo.CAMERA_FACING_BACK){
                cameraId = i;
            }
        }
        
        cameraCurrentId = cameraId;
        
        
        mSurfaceHolder.addCallback(new Callback(){
          public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
      
                      }
          public void surfaceCreated(SurfaceHolder holder) {
               // 打开摄像头
              initCamera();
                     }
          public void surfaceDestroyed(SurfaceHolder holder){
              // 如果camera不为null ,释放摄像头
              if (mCamera != null) {
            	  if (isPreview)
                       mCamera.stopPreview();
                  mCamera.release();
                  mCamera = null;
                          }
                   }
              });
        
        
 //       initCamera();
        
	//	DisplayMetrics displaysMetrics = new DisplayMetrics();  //DisplayMetrics 一个描述普通显示信息的结构，例如显示大小、密度、字体尺寸
	//	int widthSize = displaysMetrics.widthPixels;            //使用DisplayMetrics获取屏幕高的像素
	//	int tempSize = widthSize*4/3 ;                          //获取临时的预览框尺寸 	
		String filePath = "/sdcard/A_VideoTest/";      //视频保存文件夹
		String format = "mp4";                         //视频打包格式
		videoName = setVideoName(filePath,format);    //设置视频名称
		fullPath = filePath + videoName ;             //获取视频绝对路径

		buttonStart.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				recorder();
				buttonStart.setClickable(false);
				buttonStop.setClickable(true);
				buttonSwitchVideo.setClickable(false);
			}
		});

		buttonStop.setOnClickListener(new OnClickListener() {
			// @Override
			public void onClick(View v) {
				recorder.stop();
				recorder.reset();
				recorder.release();
				recorder = null;
				
				Intent toUpload = new Intent();
				toUpload.setClass(getBaseContext(), Upload.class);
				Bundle bundle  = new Bundle();
				bundle.putString("KEY_NAME", videoName);
				toUpload.putExtras(bundle);
				startActivity(toUpload);
			//	buttonStart.setClickable(true);
			//	buttonStop.setClickable(false);
			//	buttonSwitchVideo.setClickable(true);
			}
		});
	
		buttonSwitchVideo.setOnClickListener(new OnClickListener(){

			public void onClick(View v) {
				// TODO Auto-generated method stub
				   if (mCamera != null) {
	                    mCamera.stopPreview();
	                    mCamera.release();
	                    mCamera = null;
	                }
	                mCamera = Camera.open((cameraCurrentId + 1) % numCamera);
	                cameraCurrentId = (cameraCurrentId + 1) % numCamera;
	                switchCamera(mCamera);
	                mCamera.startPreview();
	                buttonStart.setClickable(true);
				
			}
		                                                       });
		
	}

	
	public void recorder() {
		try {
			recorder = new MediaRecorder();
	
			if(numCamera>1){//若是1个摄像头则直接录制
                mCamera.unlock();//要在MediaRecorder设置参数之前就调用unlock来获得camera的控制权
                recorder.setCamera(mCamera);
            }
			
			recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);//
		
			recorder.setAudioSource(MediaRecorder.AudioSource.MIC); // 
			recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);//
			recorder.setVideoSize(640,480);// 
			
			recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H263);// 
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);// 
	//		recorder.setMaxDuration(10000);// 
			recorder.setPreviewDisplay(mSurfaceHolder.getSurface());// 
			recorder.setOutputFile(fullPath);// 
		//	recorder.setVideoFrameRate(15);//
			recorder.prepare();
			recorder.start();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String setVideoName(String path,String format){            //设定文件存储目录同时命名文件
	
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}
		String tempName ="iVideo_"+getFileTime()+"."+format;
		return tempName;
	}
	
	public String getFileTime(){              //获取String型系统时间
		Date curTime = Calendar.getInstance().getTime();
		DateFormat df  = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = df.format(curTime).toString();
		return time;
	}
	
	
	
	private void initCamera(){
	if (!isPreview)
	{
	mCamera = Camera.open();
	}
	if (mCamera != null && !isPreview)
	{
	try
	{
//	Camera.Parameters parameters = mCamera.getParameters();
	
	//camera.setParameters(parameters);        //android2.3.3以后无需下步
	
	mCamera.setPreviewDisplay(mSurfaceHolder);  //通过SurfaceView显示取景画面
	
	mCamera.startPreview();           // 开始预览

	
	}
	catch (Exception e)
	{
	e.printStackTrace();
	}
	isPreview = true;
	}
	}
	
	
	   public void switchCamera(Camera camera) {
	         if(numCamera>1){//非一个摄像头
	               setCamera(camera);
	           try {
	               camera.setPreviewDisplay(mSurfaceHolder);
	            		   } catch (IOException exception) {
	                mCamera.release();
	                mCamera = null;
	           }
	 //          Camera.Parameters parameters = camera.getParameters();
	           mSurfaceView.requestLayout();
	    //       camera.setParameters(parameters);
	         }
	        
	        }
	 public void setCamera(Camera camera) {
         mCamera = camera;
         if (mCamera != null) {
             mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();//获取硬件所支持的尺寸
             mSurfaceView.requestLayout();
         }
  }

	
	
}
